﻿namespace Arms.Framework
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class ICollectionExtensions
    {
        /// <summary>
        /// Adds items to this list if it doesnt already exist in the list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static ICollection<T> AddDistinct<T>(this ICollection<T> source, params T[] items)
        {
            if (source != null)
            {
                foreach (T item in items)
                {
                    if (!source.Contains(item))
                    {
                        source.Add(item);
                    }
                }
            }

            return source;
        }
        /// <summary>
        /// Adds a distinct item to this list by distinct key.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="source"></param>
        /// <param name="key"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        public static ICollection<T> AddDistinct<T, TKey>(this ICollection<T> source, Func<T, TKey> key, params T[] items)
        {
            bool contains = true;
            contains &= source.Select(key).Count() > 0;

            if (!contains)
            {
                source.AddDistinct<T>(items);
            }
            return source;
        }
        /// <summary>
        /// Removes any item in this source collection that matches predicate.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public static ICollection<T> RemoveWhere<T>(this ICollection<T> source, Func<T, bool> predicate)
        {
            if (source != null)
            {
                var items = source.Where(predicate);

                foreach (var item in items)
                {
                    source.Remove(item);
                }
            }

            return source;
        }
    }
}